%%

clear all;
close all;

I = imread('board.png');

sz = size(I);

d = 0; % 1.5;


imshow(I);
hold on;
% plot(sz(2)/2+d, sz(1)/2, 'bx');
X = [1 sz(2)/2+d; size(I,2) sz(2)/2+d];
Y = [sz(1)/2 1; sz(1)/2 size(I,1)];
% line(X, Y, 'Color', 'g');

r = sz(2)/2+d; % radius
m = [r sz(1)/2];
phi = 0:18:360;
dphi = 9;
x1 = m(1) + r*cosd(phi-dphi);
y1 = m(2) - r*sind(phi-dphi);

x2 = m(1) + r*cosd(phi+180-dphi);
y2 = m(2) - r*sind(phi+180-dphi);

Xs = [x1; x2];
Ys = [y1; y2];

% line(Xs, Ys, 'Color', 'm');
r = r*(3/4);
while true
    [xin yin] = ginput(1);
    plot(xin, yin, 'y.');
    [theta rho] = cart2pol(xin-m(1), m(2)-yin);
    
    theta = radtodeg(theta)+9;
    if theta<0;
        theta = theta+360;
    end
    theta = ceil(theta/18);
    
    special = '';
    
   
    beye = r*(6.35/1.7)/100;
    bull = r*(15.9/1.7)/100;
    dtsz = r*(8/1.7)/100; % double/triple field size
    % triple boundaries
    tup = r*(107/1.7)/100;
    tlow = tup-dtsz;
    % double boundaries
    dup = r;% r*(3/4)/100;
    dlow = dup-dtsz;
    
    if rho <= beye
        score = 'Bull''s eye';
        theta = 0;
    elseif rho > beye && rho <= bull
        score = 'Bull';
        theta = 0;
    elseif rho >= tlow && rho <= tup
        special = 'triple';
    elseif rho >= dlow  && rho <= dup
        special = 'double';
    elseif rho > dup
        score = 'OUT';
        theta = 0;
    end        
    
    
    switch theta
        case 1
            score = '6';
        case 2
            score = '13';
        case 3
            score = '4';
        case 4
            score = '18';
        case 5
            score = '1';
        case 6
            score = '20';
        case 7
            score = '5';
        case 8
            score = '12';
        case 9
            score = '9';
        case 10
            score = '14';
        case 11
            score = '11';
        case 12
            score = '8';
        case 13
            score = '16';
        case 14
            score = '7';
        case 15
            score = '19';
        case 16
            score = '3';
        case 17
            score = '17';
        case 18
            score = '2';
        case 19
            score = '15';
        case 20
            score = '10';
        otherwise
    end
    title(sprintf('Score: %s %s, r = %5.3f', score, special, rho));
    pause(1);
end
hold off;